package servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import persistence.PersistenceUtil;

import model.Contact;
import model.ContactGroup;
import model.ContactGroupManager;

/**
 * Servlet implementation class ContactList
 */
public class ContactList extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ContactList() {
        super();
        PersistenceUtil.init();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		long cgid = Long.parseLong(request.getParameter("contactGroupSelect"));
		System.out.println("ContactList get request : "+request.toString()+" cgid : "+cgid);
		
		request.setAttribute("groupList", ContactGroupManager.getInstance().getGroupList());
		List<String> nList = new ArrayList<String>();
		List<Long> idList = new ArrayList<Long>();
		List<Contact> gList = ContactGroupManager.getInstance().getAllSortedContacts();
		for (Contact c : gList) {
			if(c.getGroup().getId() == cgid || cgid == 1){
				nList.add(c.fullName());
				idList.add(c.getId());
				System.out.println(c.fullName());
			}
		}	
		
		request.setAttribute("contactlist", nList);
		request.setAttribute("contactidlist", idList);
		request.setAttribute("currentGroup", cgid);
		request.setAttribute("content", "contactList.jsp");
		request.getRequestDispatcher("jsp/main.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
